﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;
using System.Configuration;

namespace Best.SmartCms.Config
{
    public static class ConfigurationManagerEx
    {
        /// <summary>
        /// 
        /// </summary>
        public static NameValueCollection AppSettings = new NameValueCollection();


        static ConfigurationManagerEx()
        {
            var builder = new ConfigurationBuilder();
         
            builder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"), optional: true)
                .AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "config.json"), optional: true)
                .AddJsonFile(Path.Combine(AppContext.BaseDirectory, "appsettings.json"), optional: true)
                .AddJsonFile(Path.Combine(AppContext.BaseDirectory, "config.json"), optional: true);

            var configuration = builder.Build();

            GetConfigurations(configuration);
        }


        private static void GetConfigurations(IConfiguration configuration)
        {
            var appSettings = configuration.GetChildren();
            var configurationSections = appSettings as IConfigurationSection[] ?? appSettings.ToArray();
            if (!configurationSections.Any()) return;

            foreach (var appSetting in configurationSections)
            {
                if (appSetting.Value == null)
                {
                    var section = configuration.GetSection(appSetting.Key);
                    GetConfigurations(section);
                }
                else
                {
                    AppSettings[appSetting.Path] = appSetting.Value;
                }
            }
        }
    }
}
